import { encode } from 'js-base64'
import { getWxConfig } from '@/api/index'
import { getLiveScheme } from '@/api/live'

import { VantMessage } from './vant-utils'
import { WEB_HREF } from './index'

/**
 *  微信初始化
 */
export const wxReady = () => {
  return new Promise(async(resolve, reject) => {
    try {
      // 先初始化
      await initWXConfig()
      wx.ready(() => {
        resolve()
      })
      wx.error((err) => {
        console.log('微信接口：' + JSON.stringify(err))
        reject(err)
      })
    } catch (error) {
      console.log('wxReady error >>>', error)
      reject(error)
    }
  })
}

/**
 * 初始化wx config
 *
 * @returns
 */
export const initWXConfig = () => {
  return new Promise(async(resolve, reject) => {
    // 开发环境直接通过
    if (process.env.NODE_ENV === 'development') {
      resolve()
      return
    }
    try {
      const res = await getWxConfig()
      if (res.data) {
        const { timestamp, nonceStr, signature } = res.data
        wx.config({
          beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
          // debug: true, // 开启调试
          appId: window.env.VUE_APP_APPID, // 必填，山东通的cropID
          timestamp, // 必填，生成签名的时间戳
          nonceStr, // 必填，生成签名的随机串
          signature, // 必填，签名，见附录1
          jsApiList: [
            'invoke',
            'request3rdApp',
            'openChatWithMsg',
            'shareWechatMessage',
            'shareAppMessage',
            'selectEnterpriseContact',
            'openChatWithMsg',
            'agentConfig'
          ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        })
        // 初始化成功
        resolve(res.data)
      } else {
        VantMessage.error('获取WX CONFIG失败')
        reject()
      }
    } catch (error) {
      VantMessage.error('初始化JS-SDK失败')
      reject()
    }
  })
}

/**
 * 获取应用权限
 *
 * @param {() => void} success
 * @param {() => void} fail
 */
export const wxAngentConfig = () => {
  return new Promise(async(resolve, reject) => {
    try {
      await wxReady()
      const res = await getWxConfig('agent')
      if (res.data) {
        const { timestamp, nonceStr, signature } = res.data
        wx.invoke(
          'agentConfig',
          {
            agentid: window.env.VUE_APP_AGENTID,
            corpid: window.env.VUE_APP_APPID,
            timestamp,
            nonceStr,
            signature
          },
          (res) => {
            if (res.err_msg === 'agentConfig:ok') {
              resolve()
              return
            } else {
              reject(new Error(`agentConfig error ${res.err_msg}`))
            }
          }
        )
      } else {
        reject(new Error('config data no find'))
      }
    } catch (error) {
      reject(error)
    }
  })
}

/**
 *  微信分享
 *
 * @param {object} options
 * @param {string} options.title 标题
 * @param {string} options.desc 简介
 * @param {string} options.link 链接地址
 * @param {string} options.imgUrl 缩略图
 * @param {boolean} isLive 是否直播
 * @param {(any) => {}} cb
 */
export const wxShare = async(options, isLive = true, cb = null) => {
  options = {
    title: '',
    desc: '',
    link: '',
    imgUrl: `${WEB_HREF}/assets/${isLive ? 'share-live' : 'share-video'}.png`,
    ...options
  }
  const { title, desc, link, imgUrl } = options
  try {
    await wxReady()
    wx.invoke(
      'shareAppMessage',
      {
        title, // 分享标题
        desc, // 分享描述
        link, // 分享链接
        imgUrl // 分享封面
      },
      function(res) {
        if (res.err_msg === 'shareAppMessage:ok') {
          // 执行回调
          cb && cb(res)
          return
        }
      }
    )
  } catch (error) {
    console.log('分享失败>>>', error)
  }
}

// 唤醒山东通视频会议
export const wxSdLiveApp = async(id) => {
  try {
    // 获取配置参数
    const res = await getLiveScheme(id)
    let param = res.data.param
    param = encode(JSON.stringify(param))
    await wxReady()
    wx.invoke(
      'request3rdApp',
      {
        scheme: `xylink-sdongmeeting`,
        needToken: 0,
        param
      },
      function(res) {
        if (res.err_msg === 'request3rdApp:ok') {
          console.log('拉起APP成功 >>>', res)
        } else {
          console.log('拉起APP失败 >>>', res)
        }
      }
    )
  } catch (error) {
    console.log(`拉起app失败 >>`, error)
  }
}

/**
 * 打开通讯录
 *
 * @param {Array} selectUsers
 * @param {() => {}} cb
 */
export const wxContacts = async(selectUsers, cb = null) => {
  try {
    const userList = selectUsers || []
    const selectedUserIds = userList.map((item) => item.id)
    await wxAngentConfig()
    wx.invoke(
      'selectEnterpriseContact',
      {
        fromDepartmentId: 0,
        mode: 'multi',
        type: ['user'],
        selectedUserIds
      },
      (res) => {
        if (res.err_msg === 'selectEnterpriseContact:ok') {
          if (typeof res.result === 'string') {
            res.result = JSON.parse(res.result)
          }
          cb && cb(res.result.userList || [])
        }
      }
    )
  } catch (error) {
    console.log('打开通讯录失败 >>', error)
  }
}

/**
 * 发送微信消息
 *
 * @param {Object} options
 * @param {string} options.title
 * @param {string} options.desc
 * @param {string} options.link
 * @param {Array} selectUsers
 * @param {(data) => {}} cb
 * @returns
 */
// 发送app消息
export const wxChatMsg = async(options, selectUsers, cb = null) => {
  if (!(selectUsers && selectUsers.length)) {
    cb && cb()
    return
  }
  // 单位联系人
  const userIds = selectUsers
    .filter((item) => !item.isExternal)
    .map((item) => item.id)
    .join(',')
  // 外部联系人
  const externalUserIds = selectUsers
    .filter((item) => item.isExternal)
    .map((item) => item.id)
    .join(',')
  console.log('userIds >>> ', userIds)
  console.log('externalUserIds >>> ', externalUserIds)
  try {
    await wxAngentConfig()
    wx.invoke(
      'openChatWithMsg',
      {
        userIds,
        externalUserIds,
        chatId: '',
        msg: {
          title: options.title,
          desc: options.desc,
          link: options.link,
          imgUrl: options.imgUrl || ''
        }
      },
      (res) => {
        console.log('openChatWithMsg res >>>', res)
        cb && cb(res)
      }
    )
  } catch (error) {
    console.log('发送消息失败')
    cb && cb()
  }
}
